/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pgentity;

import db.DBContext;
import java.util.Map;
import pgentity.pool.EntityFactory;
import share.PGError;
import db.PGKeys;
import db.RedisKey;
import pgentity.redis.hash.DataHash;
import share.PGException;
import share.TimeUtil;

/**
 *
 * @author KieuAnh
 */
@EntityFactory(factorier = "loadData")
public class UserDailyData extends DataHash {
    private final String uid;

    private UserDailyData(String uid, String dayToken) {
        super(key(uid, dayToken));
        this.uid = uid;
    }
    
    public static UserDailyData getData(String uid, long now)
    {
        String dayToken = TimeUtil.dayToken(now);
        return loadData(uid, dayToken);
    }
    
    private static UserDailyData loadData(String uid, String dayToken)
    {
        PGException.Assert(User.isExist(uid), PGError.INVALID_USER,
                String.format("%s doesn't exist", uid));
        
        UserDailyData userDailyData = new UserDailyData(uid, dayToken);
        return userDailyData;
    }
    
    private static RedisKey key(String uid, String dayToken)
    {
        return PGKeys.USERS.getChild(uid)
                .getChild(PGKeys.FD_DAILY_DATA)
                .getChild(dayToken);
    }
    
    @Override
    public void setData(String dataID, Object data)
    {
        DBContext.Redis().hsetENX(redisKey, dataID, String.valueOf(data),
                TimeUtil.DAY_SECS);
    }

    @Override
    public void incData(String dataID, int by) {
        DBContext.Redis().hincrbyENX(redisKey, dataID, by, TimeUtil.DAY_SECS);
    }
}
